<div id="comment" class="comment"  th:fragment="comment(name)">
  <el-form class="comment-form" :model="comment_data.formData" :rules="comment_data.rules"  label-position="top" ref="comment_form"  >
    <el-row :gutter="10">

      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
        <el-form-item prop="owner.displayName">
          <el-input placeholder="昵称（必填）" v-model="comment_data.formData.owner.displayName">
            <template #prepend><i class="bi bi-person"></i></template>
          </el-input>
        </el-form-item>
      </el-col>

      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
        <el-form-item prop="owner.email">
          <el-input placeholder="邮箱（必填）" v-model="comment_data.formData.owner.email">
            <template #prepend><i class="bi bi-envelope-at"></i></template>
          </el-input>
        </el-form-item>
      </el-col>

      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
        <el-form-item prop="owner.website">
          <el-input placeholder="网站（选填）" v-model="comment_data.formData.owner.website">
            <template #prepend><i class="bi bi-link-45deg"></i></template>
          </el-input>
        </el-form-item>
      </el-col>
       
    </el-row>

  <el-row class="comment-content">
  
    <el-form-item prop="content">
    <el-input show-word-limit maxlength="500" type="textarea" :rows="2" placeholder="请输入评论（必填）" v-model="comment_data.formData.content">
    </el-form-item>
  </el-row>
  </el-form>

  <div class="submit-btn">
    <el-button type="primary" round @click="submitComment">提交评论</el-button>
  </div>

  <el-divider content-position="left">评论区({{comment_data.comments.total}})</el-divider>

<!-- 初始化评论函数执行 -->
<div v-once style="display: none;">{{getComments(comment_data.name, 1, comment_data.pageSize)}}</div>

  <div class="comments-box">
    <el-card v-for="item in comment_data.comments.items">
      <div class="comment-item">
        <div class="left">
          <div class="avatar">
            <img :src="item.owner.avatar" v-if="item.owner.avatar">
            <div class="textAvatar"  v-if="!item.owner.avatar" >
              {{item.owner.displayName.slice(0,2)  }}
            </div>
          </div>
        </div>
        <div class="right">
          <div class="comment-info">
            <section class="name">{{item.owner.displayName}}</section>
            <el-tag size="mini" effect="plain" type="info">
              {{timestampFormat(item.metadata.creationTimestamp)}}
            </el-tag>
          </div>
          <div class="content">
            {{item.spec.content}}
          </div>
        </div>
      </div>
    </el-card>

    <div class="load">
      <el-button type="info"
      v-if="comment_data.comments.hasNext"
      @click="more(comment_data.comments.page + 1)" round>加载更多</el-button>

       <!-- <el-divider content-position="center"  
       v-if="!comment_data.comments.hasNext && comment_data.comments.total > 0"
       >
        没有更多了哦</el-divider> -->

        <el-empty 
        v-if="comment_data.comments.total == 0"
        description="评论空空如也~~~"></el-empty>
    </div>

  </div>



  <script th:inline="javascript">
    // 文章标识

    let name = [[${name}]] 
    let comment_data = {
      pageSize: 10,
      comments:{},
      name,
      formData:{
        allowNotification: "true",
        content:"",
        raw: "",
        owner:{
          displayName: "",
          email: "",
          website: ""
        },
        subjectRef:{
          group: "content.halo.run",
          kind: "Post",
          name,
          version:"v1alpha1"
        }
      },
      rules:{
        'owner.displayName':[
          { required: true, message: '要填昵称的哦', trigger: 'blur'},
          { min: 1, max:15, message: '长度在1-15', trigger: ['blur','change']}
        ],
        'owner.email':[
          { required: true, message: '要填邮箱的哦', trigger: 'blur'},
          {type: 'email', message: '别瞎填邮箱', trigger: ['blur']},
          { min: 1, max:20, message: '长度在1-20', trigger: ['blur','change']}
        ],
        'owner.website':[
          { min: 1, max:20, message: '长度在1-20', trigger: ['blur','change']}
        ],
        'content':[
          { required: true, message: '要写评论的哦', trigger: 'blur'},
          { min: 1, max:500, message: '长度在1-500', trigger: ['blur','change']}
        ],
      }
    } 

    // 读取缓存
    const owner = localStorage.getItem('owner')
    if(owner !== null) {
      comment_data.formData.owner = JSON.parse(owner)
    }

    let comment_methods = {
      // 添加评论
      submitComment(){
       // 表单校验
       this.$refs['comment_form'].validate(res => {
        if(res){
          // 缓存
          localStorage.setItem('owner',JSON.stringify(this.comment_data.formData.owner))
          // 初始化raw 
          this.comment_data.formData.raw = this.comment_data.formData.content
          // 请求必要参数
          const url = '/apis/api.halo.run/v1alpha1/comments'
          const body = JSON.stringify(this.comment_data.formData)
          const headers = {"content-type":"application/json"}
          fetch(url,{method:'post',body,headers}).then(res => {
            if(res.status == 200){
              this.message({type:'success',message:'评论成功'})
              this.comment_data.formData.content = ""
              this.comment_data.comments = {}
              this.getComments(name,1,20)
            }
          })
        }
       })
      },

      // 获取评论
      getComments(name, page, size){
        const url = `/apis/api.halo.run/v1alpha1/comments?group=content.halo.run&kind=Post&name=${name}&page=${page}&size=${size}&version=v1alpha1`
        fetch(url).then(async res => {
          if(res.status == 200){
          // 获取返回的数据
          const data = await res.json().then((data) => {return data})
          // 数据填充
          let items = this.comment_data.comments.items
          this.comment_data.comments = data
          this.comment_data.comments.items = [...items,...this.comment_data.comments.items]
          console.log('data',data)
          }
        })
      },

      // 加载更多
      more(page){
        let size = 10
        this.getComments(name, page, this.comment_data.pageSize)
      }

    }


    pageData = {comment_data, ...pageData}
    pageMethods = {...comment_methods,...pageMethods}


  </script>
</div>

